package com.example.util;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

public class UnionidUtils {

    private static final Logger LOGGER = LoggerFactory.getLogger(UnionidUtils.class);
    //互助图钉
    private static final String APPID = "wx2d1e0ea92c1f5820";
    private static final String SECRET = "218d0a9ecc76b525ca2cb60c77a7358e";


    /**
     * @param code
     * @return
     */
    public static String getUnionid(String code) {


        String URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + APPID +
                "&secret=" + SECRET + "&code=" + code + "&grant_type=authorization_code";

        RestTemplate restTemplate = new RestTemplate();
        JSONObject forObject = JSONObject.parseObject(restTemplate.getForObject(URL, String.class));
        LOGGER.info("返回信息："+forObject);
        String ACCESS_TOKEN = forObject.getString("access_token");
        String OPENID =forObject.getString("openid");
        String url ="https://api.weixin.qq.com/sns/userinfo?access_token="+ACCESS_TOKEN+"&openid="+OPENID+"&lang=zh_CN";
        JSONObject objectUnionid = JSONObject.parseObject(restTemplate.getForObject(url, String.class));
        String unionid = objectUnionid.getString("unionid");
        return unionid;
    }


    /**
     * code生成token
     * @param args
     */

    public static void main(String[] args) {

        UnionidUtils  unionidUtils =  new UnionidUtils();

        String unionid = unionidUtils.getUnionid("081DT6wm1fiyyn0AoKym18Wnwm1DT6w9");
        LOGGER.info("unionid信息："+unionid);
        if (StringUtils.isEmpty(unionid)){
            LOGGER.info("unionid为空");
        }else {
            String bulidJWT = JwtTokenUtil.createToken(unionid);
            String tokenStr = JwtTokenUtil.TOKEN_PREFIX+ bulidJWT;
            System.out.println("生成token："+tokenStr);
        }

    }

}
